﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MVVMS
{
    public static class ListUpdater
    {
        public static void UpdateContents<T>(this List<T> oc, IEnumerable<T> source)
        {
            UpdateSource<T>(oc, source);
        }

        public static void UpdateContents<T>(this ObservableCollection<T> oc, IEnumerable<T> source)
        {
            UpdateSource<T>(oc, source);
        }

        public static void UpdateSource<T>(IList<T> collection, IEnumerable<T> source)
        {
            // remove items from this list that are in current source
            List<T> toRemove = new List<T>(collection);

            // Cycle all and Add New Items
            int idx = 0;
            foreach (T sourceItem in source)
            {
                if (collection.Count > idx)
                {
                    if (!collection[idx].Equals(sourceItem))
                    {
                        var curIdx = collection.IndexOf(sourceItem);
                        if (curIdx >= 0)
                        {
                            collection.RemoveAt(curIdx);
                        }
                        collection.Insert(idx, sourceItem);
                    }
                }
                else
                    collection.Insert(idx, sourceItem);

                toRemove.Remove(sourceItem);
                idx++;
            }

            // Remove Items No Longer Needed
            foreach (T item in toRemove)
            {
                collection.Remove(item);
            }
        }
    }
}
